// 飞牛媒体库页面逻辑

// 全局变量
let currentLibrary = null;
let currentMediaItems = [];

// DOM 元素
const libraryListElement = document.getElementById('library-list');
const mediaContentElement = document.getElementById('media-content');
const mediaListElement = document.getElementById('media-list');
const selectedLibraryNameElement = document.getElementById('selected-library-name');
const backToLibrariesButton = document.getElementById('back-to-libraries');
const mediaDetailModal = document.getElementById('media-detail-modal');
const closeDetailModalButton = document.getElementById('close-detail-modal');
const detailTitleElement = document.getElementById('detail-title');
const detailTitleFullElement = document.getElementById('detail-title-full');
const detailInfoElement = document.getElementById('detail-info');
const detailOverviewElement = document.getElementById('detail-overview');
const detailTypeElement = document.getElementById('detail-type');
const detailLanguageElement = document.getElementById('detail-language');
const detailRuntimeElement = document.getElementById('detail-runtime');
const detailReleaseDateElement = document.getElementById('detail-release-date');
const detailRatingElement = document.getElementById('detail-rating');
const detailLibraryElement = document.getElementById('detail-library');
const detailPosterElement = document.getElementById('detail-poster');

// 初始化
function init() {
    // 加载媒体库列表
    loadMediaLibraries();
    
    // 添加事件监听
    backToLibrariesButton.addEventListener('click', showLibrariesView);
    closeDetailModalButton.addEventListener('click', closeDetailModal);
    mediaDetailModal.addEventListener('click', (e) => {
        if (e.target === mediaDetailModal) {
            closeDetailModal();
        }
    });
}

// 加载媒体库列表
function loadMediaLibraries() {
    // 显示加载状态
    libraryListElement.innerHTML = `
        <div class="col-span-full py-8 text-center text-gray-500">
            <i class="fa fa-refresh fa-spin text-xl mb-2"></i>
            <p>正在加载媒体库...</p>
        </div>
    `;
    
    // 发送API请求获取媒体库列表
    fetch('/api/fnos_media/library-list')
        .then(response => {
            // 即使状态码不是200，也尝试解析JSON响应
            return response.json().then(data => {
                if (!response.ok) {
                    // 如果有错误信息，使用它；否则使用状态码
                    throw new Error(data.message || `HTTP错误! 状态码: ${response.status}`);
                }
                return data;
            });
        })
        .then(data => {
            // 安全检查响应数据
            if (!data || typeof data !== 'object') {
                throw new Error('无效的响应数据格式');
            }
            
            if (data.success) {
                // 确保data.data是数组格式
                const libraries = Array.isArray(data.data) ? data.data : [];
                
                if (libraries.length > 0) {
                    renderLibraryList(libraries);
                } else {
                    libraryListElement.innerHTML = `
                        <div class="col-span-full py-8 text-center text-gray-500 empty-state">
                            <i class="fa fa-film"></i>
                            <h3>未找到媒体库</h3>
                            <p>请检查飞牛媒体库连接配置</p>
                        </div>
                    `;
                }
            } else {
                throw new Error(data.message || '获取媒体库失败');
            }
        })
        .catch(error => {
            console.error('加载媒体库失败:', error);
            // 显示友好的错误信息
            libraryListElement.innerHTML = `
                <div class="col-span-full py-8 text-center text-red-500 empty-state">
                    <i class="fa fa-exclamation-circle"></i>
                    <h3>加载失败</h3>
                    <p>${error.message || '无法连接到飞牛媒体库，请检查配置和网络连接'}</p>
                </div>
            `;
        });
}

// 存储已加载的拼接封面URL，用于后续清理
let loadedStitchedPosters = [];

// 清理临时文件
function cleanupTempFiles() {
    // 向后端发送清理请求
    fetch('/api/fnos_media/cleanup-temp', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ files: loadedStitchedPosters })
    }).catch(error => {
        console.warn('清理临时文件失败:', error);
    });
    
    // 清空已加载的封面列表
    loadedStitchedPosters = [];
}

// 添加页面切换和关闭时的清理
window.addEventListener('beforeunload', cleanupTempFiles);
backToLibrariesButton.addEventListener('click', cleanupTempFiles);

// 渲染媒体库列表
function renderLibraryList(libraries) {
    libraryListElement.innerHTML = '';
    
    libraries.forEach(library => {
        const libraryItem = document.createElement('div');
        libraryItem.className = 'library-item';
        libraryItem.setAttribute('data-guid', library.guid);
        
        // 获取第一张海报作为初始封面
        const initialPosterUrl = library.posters && library.posters.length > 0 
            ? library.posters[0] 
            : '/static/images/placeholder.png';
        
        libraryItem.innerHTML = `
            <div class="relative">
                <img src="${initialPosterUrl}" alt="${library.title}" class="library-poster object-cover w-full h-40">
                <div class="absolute inset-0 bg-gradient-to-t from-black/70 to-transparent flex items-end">
                    <div class="p-3 text-white">
                        <div class="font-bold text-lg">${library.title}</div>
                        <div class="text-sm opacity-90">媒体库ID: ${library.guid}</div>
                    </div>
                </div>
            </div>
        `;
        
        // 尝试加载拼接后的封面
        fetchStitchedPoster(library.guid, libraryItem);
        
        libraryItem.addEventListener('click', () => {
            loadMediaItems(library.guid, library.title);
        });
        
        libraryListElement.appendChild(libraryItem);
    });
}

// 获取并应用拼接后的封面
function fetchStitchedPoster(libraryGuid, libraryItem) {
    fetch(`/api/fnos_media/library-poster?library_guid=${encodeURIComponent(libraryGuid)}`)
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP错误! 状态码: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            if (data.success && data.poster_url) {
                // 更新封面图片
                const imgElement = libraryItem.querySelector('.library-poster');
                if (imgElement) {
                    imgElement.src = data.poster_url;
                    
                    // 添加到已加载列表以便后续清理
                    loadedStitchedPosters.push(data.poster_url);
                }
            }
        })
        .catch(error => {
            console.warn(`加载媒体库拼接封面失败 (${libraryGuid}):`, error);
            // 失败时保持初始封面不变
        });
}

// 加载媒体条目
function loadMediaItems(libraryGuid, libraryName) {
    currentLibrary = { guid: libraryGuid, name: libraryName };
    
    // 显示媒体内容区域
    libraryListElement.parentElement.classList.add('hidden');
    mediaContentElement.classList.remove('hidden');
    selectedLibraryNameElement.textContent = `${libraryName} - 媒体内容`;
    
    // 显示加载状态
    mediaListElement.innerHTML = `
        <div class="col-span-full py-8 text-center text-gray-500">
            <i class="fa fa-refresh fa-spin text-xl mb-2"></i>
            <p>正在加载媒体内容...</p>
        </div>
    `;
    
    // 发送API请求获取媒体内容
    fetch(`/api/fnos_media/media-list?library_guid=${encodeURIComponent(libraryGuid)}`)
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP错误! 状态码: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            if (data.success && data.data && data.data.length > 0) {
                currentMediaItems = data.data;
                renderMediaItems(data.data);
            } else {
                mediaListElement.innerHTML = `
                    <div class="col-span-full py-8 text-center text-gray-500 empty-state">
                        <i class="fa fa-film"></i>
                        <h3>该媒体库中暂无内容</h3>
                        <p>请尝试选择其他媒体库</p>
                    </div>
                `;
            }
        })
        .catch(error => {
            console.error('加载媒体内容失败:', error);
            mediaListElement.innerHTML = `
                <div class="col-span-full py-8 text-center text-red-500 empty-state">
                    <i class="fa fa-exclamation-circle"></i>
                    <h3>加载失败</h3>
                    <p>无法获取媒体内容，请稍后重试</p>
                </div>
            `;
        });
}

// 渲染媒体条目
function renderMediaItems(mediaItems) {
    mediaListElement.innerHTML = '';
    
    mediaItems.forEach(item => {
        const mediaItem = document.createElement('div');
        mediaItem.className = 'media-item';
        mediaItem.setAttribute('data-guid', item['唯一标识']);
        
        // 获取海报URL，如果没有则使用占位图
        const posterUrl = item['海报完整URL'] && item['海报完整URL'] !== '' 
            ? item['海报完整URL'] 
            : '/static/images/placeholder.png';
        
        mediaItem.innerHTML = `
            <img src="${posterUrl}" alt="${item['标题']}" class="media-poster">
            <div class="media-info">
                <div class="media-title">${item['标题']}</div>
                <div class="media-meta">
                    <div>${item['类型']} · ${item['发行日期']}</div>
                    <div>评分: ${item['评分']}</div>
                </div>
            </div>
        `;
        
        mediaItem.addEventListener('click', () => {
            showMediaDetail(item);
        });
        
        mediaListElement.appendChild(mediaItem);
    });
}

// 显示媒体详情
function showMediaDetail(mediaItem) {
    detailTitleElement.textContent = mediaItem['标题'];
    detailTitleFullElement.textContent = mediaItem['标题'];
    detailInfoElement.textContent = `${mediaItem['类型']} · ${mediaItem['发行日期']} · ${mediaItem['时长(分钟)']}分钟`;
    detailOverviewElement.textContent = mediaItem['剧情简介'];
    detailTypeElement.textContent = mediaItem['类型'];
    detailLanguageElement.textContent = mediaItem['语言'];
    detailRuntimeElement.textContent = mediaItem['时长(分钟)'];
    detailReleaseDateElement.textContent = mediaItem['发行日期'];
    detailRatingElement.textContent = mediaItem['评分'];
    detailLibraryElement.textContent = mediaItem['所属媒体库名称'];
    
    // 设置海报图片
    const posterUrl = mediaItem['海报完整URL'] && mediaItem['海报完整URL'] !== '' 
        ? mediaItem['海报完整URL'] 
        : '/static/images/placeholder.png';
    detailPosterElement.src = posterUrl;
    detailPosterElement.alt = mediaItem['标题'];
    
    // 显示详情弹窗
    mediaDetailModal.classList.remove('hidden');
    document.body.style.overflow = 'hidden'; // 防止背景滚动
}

// 关闭媒体详情弹窗
function closeDetailModal() {
    mediaDetailModal.classList.add('hidden');
    document.body.style.overflow = ''; // 恢复背景滚动
}

// 显示媒体库视图
function showLibrariesView() {
    mediaContentElement.classList.add('hidden');
    libraryListElement.parentElement.classList.remove('hidden');
    currentLibrary = null;
    currentMediaItems = [];
}

// 测试飞牛媒体库连接
function checkFeiniuConnectivity() {
    const statusElement = document.getElementById('fnos-media-connectivity-status');
    
    if (statusElement) {
        // 更新状态为检查中
        updateStatusElement(statusElement, 'info', '检测中...');
    }
    
    // 发送连接测试请求
    fetch('/api/fnos_media/test-connection')
        .then(response => response.json())
        .then(data => {
            if (statusElement) {
                if (data.success) {
                    // 连接成功
                    updateStatusElement(statusElement, 'success', '已连接');
                } else {
                    // 连接失败
                    updateStatusElement(statusElement, 'error', data.message || '未连接');
                }
            }
        })
        .catch(error => {
            if (statusElement) {
                updateStatusElement(statusElement, 'error', '连接失败');
            }
        });
}

// 初始化页面
document.addEventListener('DOMContentLoaded', init);

// 导出函数供其他模块使用（如main.js中的连接测试）
window.checkFeiniuConnectivity = checkFeiniuConnectivity;